package org.example.mylogin.service.impl;


import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.mylogin.dto.AdminLoginDTO;
import org.example.mylogin.entity.Admin;
import org.example.mylogin.mapper.AdminMapper;
import org.example.mylogin.service.AdminService;
import org.example.mylogin.utils.BaseContext;
import org.example.mylogin.utils.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author mylogin
 * @since 2024-04-16
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate redisTemplate;


    @Resource
    private HttpServletRequest request;

    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        //判断是否正确
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getPhone,adminLoginDTO.getPhone());
        Admin admin = this.getOne(queryWrapper);
        if(admin == null)
        {
            log.info("手机号{}不存在",adminLoginDTO.getPhone());
            throw new RuntimeException("用户名或者密码不存在");
        }
        //加密
        String password = BCrypt.hashpw(adminLoginDTO.getPassword());
        log.info("password:{}", password);

        if(!BCrypt.checkpw(adminLoginDTO.getPassword(),admin.getPassword()))
        {
            log.info("手机号{}错误,密码{}错误",adminLoginDTO.getPhone(),adminLoginDTO.getPassword());
            throw new RuntimeException("用户名或者密码不存在");
        }

//        if(!admin.getPassword().equals(adminLoginDTO.getPassword()))
//        {
//             log.info("密码错误");
//             throw new RuntimeException("用户名或者密码不存在");
//        }这样判断密码错误
        //签发token
        String token = jwtUtil.createJwt(admin.getAdminId());

        //存入redis
        redisTemplate.opsForValue().set("adminLogin:token",token,40, TimeUnit.SECONDS);

        return token;
    }

    @Override
    public Admin getAdminInfo() {

        String id = BaseContext.get();
        //获取admin
        Admin admin = this.getById(id);
        return admin;
    }
}
